package com.chihb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chihb.domain.LoginUser;
import com.chihb.domain.User;
import com.chihb.mapper.MenuMapper;
import com.chihb.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author chihb
 * @create-time 2024/11/29 9:45
 * @description
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户信息：注意使用我们自己定义的User实体类，别导错包
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        wrapper.eq("user_name", username);
        User user = userMapper.selectOne(wrapper);

         //如果查询不到数据就通过抛出异常来给出提示
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户名错误");
        }

        // 从数据库查询权限信息
        List<String> list =  menuMapper.selectPermsByUserId(user.getId());

        //封装成UserDetails对象返回
        return new LoginUser(user,list);
    }
}
